package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	m1 := msgGen("service01")
	//m2 := msgGen("service02")
	for {
		//m := fanIn(m1, m2)
		//fmt.Println(<-m)
		if wait, b := waitTimeOut(m1, time.Millisecond*2000); b {
			fmt.Println(wait)
		} else {
			fmt.Println("timeout")
		}
	}
}

// 非阻塞等待
func noBlockingWait(c chan string) (string, bool) {
	select {
	case m := <-c:
		return m, true
	default:
		return "", false
	}
}

func waitTimeOut(c chan string, timeout time.Duration) (string, bool) {
	select {
	case m := <-c:
		return m, true
	case <-time.After(timeout):
		return "", false
	}
}

func fanIn(chs ...chan string) chan string {
	c := make(chan string)
	for _, ch := range chs {
		go func(ch chan string) {
			for {
				c <- <-ch
			}
		}(ch)
	}
	return c
}

func msgGen(serviceName string) chan string {
	c := make(chan string)

	go func() {
		n := 0
		for {
			time.Sleep(time.Duration(rand.Intn(5000)) * time.Millisecond)
			c <- fmt.Sprintf("message %s %d", serviceName, n)
			n++
		}
	}()
	return c
}
